<?php
/**
 * 获取订单数据写入数据库
 * Created by wzb.
 * User: wzb
 * time:2017/08/11
 */

/************处理订单信息*******************/
/**接收数据的参数名 items
*
*/

require("interface.php");
require_once('/home/paypal/GetTransactionDetails.php');
echo "setp: 1 get account info!\n";
echo "setp: foreach store\n";
$app_info = "select * from dlz_account_info where status='1'";
$query = $db->query($app_info);//返回影响了多少行数据
//循环获取店铺信息，轮询获取订单
while($row = $query->fetch()){
        $id_m = $row['id'];
        $store_name_m = $row['store_name'];
        $token_m = $row['token'];
        $baseUrl_m = $row['baseUrl'];
        $username_m = $row['username'];
        $password_m = $row['password'];
        $paypal_user = $row['paypal_user'];
        $paypal_pwd = $row['paypal_pwd'];
        $paypal_signature = $row['paypal_signature'];
        $Mazentop = new Mazentop($token_m,$baseUrl_m,$username_m,$password_m);
        echo "setp: 2 start get orderid [$store_name_m]\n";
        //取出订单列表中已存在的最大
        $sync_max_id = "select max(id) from dlz_attribute_all_id where store_id = '$id_m'";
        $sync_max_query = $db->query($sync_max_id);//返回影响了多少行数据
        while($row = $sync_max_query->fetch()){
             $maxid = $row[0];
        } 
        $sync_id = "select orderid from dlz_attribute_all_id where id = '$maxid'";
        $sync_query = $db->query($sync_id);//返回影响了多少行数据
        while($row = $sync_query->fetch()){
                $befoorderid = $row['orderid'];
          }
        //一次只去获取100单
        for($i=1;$i<=20;$i++){
          $startorderid = $befoorderid + $i;
          $status = Getorderinfo($Mazentop,$id_m,$store_name_m,$db,$orderid=$startorderid,$paypal_user,$paypal_pwd,$paypal_signature);
          $newadd = $startorderid-$befoorderid;
          $newadds = $newadd-1;
          if($status == '2'){
            $nextstatus = '2';//2代表自定义值，未获取到数据，停止循环
            continue;
          }else{
            $nextstatus = '1';
          }
        }
        if($nextstatus == '2' && $newadds !== 0){
           /*同步记录*/
           //-1 代表此次未增加任何数据
          //$newadd = $startorderid-$befoorderid;
          $syncdata = array(
            'new_add_num' => "$newadds",
            'store_name' => $store_name_m,
            'storeid' => $id_m,
            'lastorderid' => $startorderid,
            'orderidstoreid' => $startorderid.'-'.$id_m
        );
        $table = 'dlz_sync_ordernums';
        echo "********************write sync info ******************** \n";

        Getinsert($arrData=$syncdata,$table,$db,$sync_data="0");//
        //return true;
        }

       
    }
/**
 * [Getorderinfo description] 获取订单
 * @param [type] $Mazentop     [API]
 * @param [type] $id_m         [店铺id]
 * @param [type] $store_name_m [店铺名称]
 * @param [type] $db           [DB]
 * @param [type] $orderid      [订单id]
 */
function Getorderinfo($Mazentop,$id_m,$store_name_m,$db,$orderid,$paypal_user,$paypal_pwd,$paypal_signature){
       $UpdateTime = date('Y-m-d H:i:s');
       $data = $Mazentop->Byid($id=$orderid);
       if(array_key_exists('message',$data) || array_key_exists('error',$data)){
        return $status='2';//获取不到数据，返回自定义数值
       }
       $increment_id = $data['increment_id'] ;//订单号
       $entity_id = $data['entity_id'] ;//order
      //$store_id = $data['store_id'] ;//店铺id ,目前先使用高清写死的shopid
       $store_id = $id_m;//店铺id
       $store_name_str = $data['store_name'] ;//店铺名字
       $store_name = str_replace(array("\r\n", "\r", "\n"), " ", $store_name_str);
       $status = $data['status'] ;//订单状态
       $base_grand_total = $data['base_grand_total'] ;//订单总金额
       $base_shipping_amount = $data['base_shipping_amount'] ;//运费
       $base_total_paid = !empty($data['base_total_paid']) ? $data['base_total_paid'] : null;//付款金额
       $order_currency_code = $data['order_currency_code'] ;//订单币种
       $total_item_count = $data['total_item_count'] ;//子订单数量
       $total_qty_ordered = $data['total_qty_ordered'] ;//产品数量
       $subtotal = $data['subtotal'] ;//总金额包括运费
       $discount_amount = $data['discount_amount'] ;//总折扣
       $discount_description = !empty($data['discount_description']) ? $data['discount_description'] : null;//折扣名称

       $weight = $data['weight'] ;//产品总重量
       $created_at = $data['created_at'] ;//订单创建时间
       $updated_at = $data['updated_at'] ;//订单修改时间
       $remote_ip = $data['remote_ip'] ;//登录ip
       $customer_is_guest = $data['customer_is_guest'] ;//是否是游客
       $items = $data['items'] ;//子订单信息
       /*
       foreach ($items as $key => $value) {
           $child_created_at = $value['created_at'] ;//创建时间
           $child_name = $value['name'] ;//商品名称
           $child_sku = $value['sku'] ;//商品名称
           $child_order_id = $value['order_id'] ;//订单id
           $child_updated_at = $value['updated_at'] ;//更新时间
      }
      */
       $billing_address = $data['billing_address'];//账单地址
       $billing_address_address_type = $billing_address['address_type'];//账单
       $billing_address_city = addslashes($billing_address['city']);//城市
       $billing_address_company = !empty($billing_address['company']) ? addslashes($billing_address['company']) : null;//公司
       $billing_address_country_id = $billing_address['country_id'];//国家编码
       $billing_address_email = addslashes($billing_address['email']);//邮件地址
       $billing_address_firstname = addslashes($billing_address['firstname']);//名字
       $billing_address_lastname = addslashes($billing_address['lastname']);//姓氏
       $billing_address_postcode = addslashes($billing_address['postcode']);//邮编
       $billing_address_region = addslashes($billing_address['region']);//地区
       $billing_address_region_code = $billing_address['region_code'];//地区编码
       $billing_address_street = $billing_address['street'];//街道
       $billing_street = addslashes(implode(" ",$billing_address_street));
       $billing_address_telephone = addslashes($billing_address['telephone']);//电话
       /***买家信息写入数据库****/
       $BuyerData = array(
            'store_id' => $id_m,
            'store_name' => $store_name_m,
            'telephone' => $billing_address_telephone,
            'country' => $billing_address_country_id,
            'region' => $billing_address_region,
            'email' => $billing_address_email,
            'firstName' => $billing_address_firstname,
            'lastName' => $billing_address_lastname,
            'remote_ip' => $remote_ip,
            'is_guest' => $customer_is_guest,
            'updatetime' => $UpdateTime
            );
        $table_buyer = 'dlz_buyer_info';
        echo "********************write mysql  buyer******************** \n";
        Getinsert($arrData=$BuyerData,$table=$table_buyer,$db,$sync_data="0");//

      /******付款部分**********/
       $payment = $data['payment'];//付款
       $payment_account_status = $payment['account_status'];//账户状态
       $additional_information = $payment['additional_information'];//付款返回值
       $pay_info_status = !empty($additional_information[0]) ? $additional_information[0] : null;//
       $pay_info_nul = !empty($additional_information[1]) ? $additional_information[1] : null;
       $pay_id = !empty($additional_information[2]) ? $additional_information[2] : null;//Payer ID
       $pay_Email = !empty($additional_information[3]) ? $additional_information[3] :null;//Payer Email:
       $pay_Status = !empty($additional_information[4]) ? $additional_information[4] :null;//Payer Status:
       $pay_address_status = !empty($additional_information[5]) ? $additional_information[5] : null;//Payer Address Status:
       $pay_LastCorrelationID = !empty($additional_information[6]) ? $additional_information[6] : null;//相关id
       $pay_EC = !empty($additional_information[8]) ? $additional_information[8] : null;//未知参数
       $pay_MPE = !empty($additional_information[11]) ? $additional_information[11] : null;//Merchant Protection Eligibility
       $pay_result = !empty($additional_information[12]) ? $additional_information[12] : null;//支付结果

/*
       $payment_amount_ordered = $payment['amount_ordered'];//应付款金额
      // $payment_base_amount_ordered = $payment['base_amount_ordered'];//实际付款金额
       $payment_shipping_amount = $payment['shipping_amount'];//应付邮费金额
       //$payment_base_shipping_amount = $payment['base_shipping_amount'];//实际邮费金额
       */
       $payment_method = $payment['method'];//付款方式
       $amount_refunded = !empty($payment['amount_refunded']) ? $payment['amount_refunded'] : null;//退款金额
       $payment_last_trans_id = !empty($payment['last_trans_id']) ? $payment['last_trans_id'] : null;//交易id
/***********写入数据库**************************/
      $Order_Data = array(
            'increment_id' => $increment_id,
            'store_id' => $store_id,
            'store_name' => $store_name,
            'status' => $status,
            'subtotal' => $subtotal,
            'base_grand_total' => $base_grand_total,
            'base_shipping_amount' => $base_shipping_amount,
            'base_total_paid' => $base_total_paid,
            'discount_amount' => $discount_amount,
            'discount_description' => $discount_description,
            'order_currency_code' => 'USD',//$order_currency_code,
            'amount_refunded' => $amount_refunded,
            'payment_method' => $payment_method,
            'payment_last_trans_id' => $payment_last_trans_id,
            'total_item_count' => $total_item_count,
            'total_qty_ordered' => $total_qty_ordered,
            'weight' => $weight,
            'created_at' => $created_at,
            'updated_at' => $updated_at,
            'updatetime' => $UpdateTime
           
      );
        $table = 'dlz_order_info';
        echo "********************write mysql order******************** \n";
        Getinsert($arrData=$Order_Data,$table,$db,$sync_data='0');//
        echo "********************通过paypal 获取净额******************** \n";
        /***********通过paypal 获取净额***************/
        if(!empty($payment_last_trans_id)){
             $netdata = GetOrderPaypalNet($paypalid = $payment_last_trans_id,$paypal_user,$paypal_pwd,$paypal_signature);
             update($table='dlz_order_info',$arrData=$netdata,$filed='payment_last_trans_id',$fileddata=$payment_last_trans_id,$db);
            // Getinsert($arrData=$netdata,$table='dlz_order_info',$db,$sync_data="0");//
        }

       $extension_attributes = $data['extension_attributes']['shipping_assignments'];//扩展信息
       /*******************寄送地址******************/
       foreach ($extension_attributes as $key => $value) {
           $extension_shipping = $value['shipping']['address'];//物流信息
           $extension_attributes_address_type = $extension_shipping['address_type'];//地址类型
           $extension_attributes_city = addslashes($extension_shipping['city']);//城市
           $extension_attributes_company = !empty($extension_shipping['company']) ? addslashes($extension_shipping['company']) : null;//公司
           $extension_attributes_country_id = $extension_shipping['country_id'];//国家编码
           $extension_attributes_email = addslashes($extension_shipping['email']);//邮件地址
           $extension_attributes_firstname = addslashes($extension_shipping['firstname']);//名字
           $extension_attributes_lastname = addslashes($extension_shipping['lastname']);//姓氏
           $extension_attributes_postcode = addslashes($extension_shipping['postcode']);//邮编
           $extension_attributes_region = addslashes($extension_shipping['region']);//地区
           $extension_attributes_region_code = $extension_shipping['region_code'];//地区编码
           $extension_attributes_street = $extension_shipping['street'];//街道
           $shipping_street = addslashes(implode("__",$extension_attributes_street));
           $extension_attributes_telephone = addslashes($extension_shipping['telephone']);//电话
            $extension_shipping = $value['shipping']['total'];//物流金额
            $shipping_amount = $extension_shipping['shipping_amount'];
          /***寄送地址写入数据库****/
          $ShippingData = array(
            'increment_id' => $increment_id,
            'store_id' => $id_m,
            'store_name' => $store_name_m,
            'shipping_amount' => $shipping_amount,
            'order_currency_code' => $order_currency_code,
            'shipping_street' => $shipping_street,
            'city' => $extension_attributes_city,
            'company' => $extension_attributes_company,
            'entity_id' => $entity_id,
            'country_id' => $extension_attributes_country_id,
            'email' => $extension_attributes_email,
            'firstname' => $extension_attributes_firstname,
            'lastname' => $extension_attributes_lastname,
            'postcode' => $extension_attributes_postcode,
            'region' => $extension_attributes_region,
            'region_code' => $extension_attributes_region_code,
            'telephone' => $extension_attributes_telephone,
            'updatetime' => $UpdateTime,
            'shopid_ent' => $increment_id.'_'.$entity_id
      );
      
        $table_ship = 'dlz_shipping_info';
        echo "********************write mysql  shipping******************** \n";
        //print_r($ShippingData);
      Getinsert($arrData=$ShippingData,$table=$table_ship,$db,$sync_data="0");

     $extension_attributes_shipping_assignments_items = $value['items'];//订单物流货品信息
        foreach ($extension_attributes_shipping_assignments_items as $key => $values) {
            $items_created_at = $values['created_at'];//订单物流货品信息
            $items_name = $values['name'];//产品名
            $order_id = $values['order_id'];//orderid
            $items_product_id = $values['product_id'];//产品id
            $items_product_type = $values['product_type'];//产品类型
            $items_sku = $values['sku'];//sku
            $items_store_id = $values['store_id'];//商店id
            $items_created_at = $values['created_at'];//创建时间
            $items_updated_at = $values['updated_at'];//更新时间
            $item_price = $values['price'];//单个item产品总价
            $items_item_id = $values['item_id'];//item_id
            $qty_ordered = $values['qty_ordered'];//条数
       /***买家信息写入数据库****/
       $ProductitemData = array(
            'store_id' => $id_m,
            'store_name' => $store_name_m,
            'increment_id' => $increment_id,
            'product_id' => $items_product_id,
            'sku' => $items_sku,
            'item_id' => $items_item_id,
            'orderid' => $order_id,
            'storeanditem' => $id_m.'_'.$items_item_id,
            'price' => $item_price,
            'pice_or_lotnums' => $qty_ordered,
            'sync_status' => '0',//默认给2,因为未找到 同步option后 不改变为0，目前先给0
            'updatetime' => $UpdateTime
            );
        $table_item = 'dlz_attribute_all_id';
        echo "********************write mysql  items******************** \n";
        Getinsert($arrData=$ProductitemData,$table=$table_item,$db,$sync_data="0");//
        $insert_statu_Y = "update dlz_order_info set orderid='$order_id' where increment_id='$increment_id'";
        $checkStatus = $db->exec($insert_statu_Y);//如果出现 400 500，则不在推送。storeid
        //echo "....$items_store_id";
        }//extension_attributes_shipping_assignments_items 循环结尾
  }//shipping_assignments 循环结尾



 echo "++++++++++++++++++end++++++++++++++++++++\n"  ; 
 return 3;
}//function
$db = null;

//include("getorderproductoptionsid.php");


